package com.gsc.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gsc.domain.ResponseResult;
import com.gsc.domain.dto.MenuListDto;
import com.gsc.domain.entity.Menu;
import com.gsc.domain.vo.MenuTreeVo;
import com.gsc.domain.vo.RoleMenuTreeSelectVo;
import com.gsc.enums.AppHttpCodeEnum;
import com.gsc.exception.SystemException;
import com.gsc.service.MenuService;
import com.gsc.utils.SystemConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜单管理接口
 * @author gscstart
 * @create 2023/2/21-15:49
 */
@RestController
@RequestMapping("/system/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @GetMapping("/list")
    public ResponseResult selectMenuList(MenuListDto menuListDto){
        List<Menu> menus = menuService.selectMenuList(menuListDto);
        return ResponseResult.okResult(menus);
    }

    @PostMapping
    public ResponseResult addMenu(@RequestBody Menu menu){
        menuService.save(menu);
        return ResponseResult.okResult();
    }

    /**
     * 根据菜单id查询数据回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ResponseResult selectMenu(@PathVariable("id") Long id){
        Menu menu = menuService.selectMenu(id);
        return ResponseResult.okResult(menu);
    }

    @PutMapping
    public ResponseResult updateMenu(@RequestBody Menu menu){
        if(menu.getParentId().equals(menu.getId()) ){
            return ResponseResult.errorResult(500,"修改菜单'" +menu.getMenuName()+ "'失败，上级菜单不能选择自己");
        }

        menuService.updateMenu(menu);
        return ResponseResult.okResult();
    }

    @DeleteMapping("/{menuId}")
    public ResponseResult deleteMenu(@PathVariable("menuId") Long menuId){
        if(menuService.hasChild(menuId)){
            return ResponseResult.errorResult(500,"存在子菜单不允许删除");
        }
        menuService.removeById(menuId);
        return ResponseResult.okResult();
    }

    /**
     * TODO 获取菜单下拉树列表(新增、修改角色时用到)
     * @return
     */
    @GetMapping("/treeselect")
    public ResponseResult treeSelectMenu(){
        List<Menu> menus = menuService.treeSelectMenu(new Menu());
        List<MenuTreeVo> options =  SystemConverter.buildMenuSelectTree(menus);
        return ResponseResult.okResult(options);
    }

    /**
     * 加载对应角色菜单列表树接口
     */
    @GetMapping("/roleMenuTreeselect/{id}")
    public ResponseResult roleMenuTreeselect(@PathVariable("id") Long id){
        //查询所有菜单集合
        List<Menu> menus = menuService.treeSelectMenu(new Menu());
        //查询角色拥有的菜单集合id
        List<Long> checkedKeys = menuService.selectMenuListByRoleId(id);
        List<MenuTreeVo> options =  SystemConverter.buildMenuSelectTree(menus);
        //封装vo返回
        RoleMenuTreeSelectVo vo = new RoleMenuTreeSelectVo(checkedKeys,options);
        return ResponseResult.okResult(vo);
    }


}
